home *** CD-ROM | disk | FTP | other *** search
- Path: castle.nando.net!news
- From: actuary@nando.net (Bill McCarthy)
- Newsgroups: comp.lang.c
- Subject: Re: truncation function?
- Date: 12 Feb 1996 02:21:32 GMT
- Organization: News & Observer Public Access
- Message-ID: <4fm87c$6mi@castle.nando.net>
- References: <4fjc0k$nev$1@mhadg.production.compuserve.com>
- Reply-To: actuary@nando.net (Bill McCarthy)
- NNTP-Posting-Host: grail2419.nando.net
- X-Newsreader: IBM NewsReader/2 v1.2
-
- In <4fjc0k$nev$1@mhadg.production.compuserve.com>, Steve Eckmann <71055.1153@CompuServe.COM> writes:
- >I need a truncation function "float trunc(float in; int precision)" that
- >takes a float and a precision spec and returns the input float truncated to
- >"precision" decimal digits. Similarly for "round". This seems so simple
- >that I hesitate to ask, but on the other hand, my attempt (using sprintf
- >and sscanf) yields incorrect results sometimes. Thanks.
-
- Here's a sample trunc() function which uses doubles instead of floats:
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
-
- double trunc( double x, int n ) /* rounds toward zero */
- {
- double pown;
- static double power[] = { 1, 10, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
- 1E9, 1E10, 1E11, 1E12, 1E13, 1E14 };
-
- if ( n < 0 || n >= sizeof( power ) / sizeof( power[0] ) )
- {
- fprintf( stderr, "trunc() precision range error.\n" );
- exit( EXIT_FAILURE );
- }
-
- pown = power[n];
-
- if ( x < 0 )
- return -floor( -x * pown ) / pown;
- else
- return floor( x * pown ) / pown;
- }
-
- Bill McCarthy
- actuary@nando.net
- Wendell, NC USA
-
-